package com.lyhengtongwl.zqsnews.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowInsets;

import com.alibaba.fastjson.JSONObject;
import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.entity.NewsBaseEntity;
import com.lyhengtongwl.zqsnews.net.MyCallback;
import com.lyhengtongwl.zqsnews.net.Task;
import com.lyhengtongwl.zqsnews.utils.AppConfig;
import com.lyhengtongwl.zqsnews.utils.NewsToastUtils;
import com.lyhengtongwl.zqsnews.utils.PermissionUtils;
import com.lyhengtongwl.zqsnews.utils.SPUtils;
import com.lyhengtongwl.zqsnews.utils.SystemUtils;
import com.lyhengtongwl.zqsnews.utils.UserUtils;
import com.lyhengtongwl.zqsnews.widget.CenterDialog;

import java.lang.ref.WeakReference;

import retrofit2.Response;


/**
 * 欢迎页
 */
public class WelActivity extends AppCompatActivity {
    //定义需要申请的相关权限
    private final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE,
    };
    //    Manifest.permission.READ_PHONE_STATE,
//    Manifest.permission.ACCESS_FINE_LOCATION,
//    Manifest.permission.WAKE_LOCK,
//    Manifest.permission.WRITE_CONTACTS,
//    Manifest.permission.WRITE_EXTERNAL_STORAGE
    private MyHandler myHandler;

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!isTaskRoot()) {
            finish();
            return;
        }
        setContentView(R.layout.activity_wel);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            View decorView = window.getDecorView();
            decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
                @TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
                @Override
                public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                    WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
                    return defaultInsets.replaceSystemWindowInsets(
                            defaultInsets.getSystemWindowInsetLeft(),
                            0,
                            defaultInsets.getSystemWindowInsetRight(),
                            defaultInsets.getSystemWindowInsetBottom());
                }
            });
            ViewCompat.requestApplyInsets(decorView);
            //将状态栏设成透明，如不想透明可设置其他颜色
            window.setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
        }
//        myHandler = new MyHandler(this);
//        //获取系统参数

        getConfig();
    }

    //保存数据
    private void saveConfig(JSONObject configJsonObject, JSONObject cusJsonObject) {
        AppConfig.getInstance(App.getContext()).set("privacyUrl", configJsonObject.getString("privacyUrl"));
        AppConfig.getInstance(App.getContext()).set("downLoadUrl", configJsonObject.getString("downLoadUrl"));
        AppConfig.getInstance(App.getContext()).set("strategyUrl", configJsonObject.getString("strategyUrl"));
        AppConfig.getInstance(App.getContext()).set("userUrl", configJsonObject.getString("userUrl"));
        AppConfig.getInstance(App.getContext()).set("newUrl", configJsonObject.getString("newUrl"));
        AppConfig.getInstance(App.getContext()).set("shareQQUrl", configJsonObject.getString("shareQQUrl"));
        AppConfig.getInstance(App.getContext()).set("shareUrl", configJsonObject.getString("shareUrl"));
        AppConfig.getInstance(App.getContext()).set("signUrl", configJsonObject.getString("signUrl"));
        AppConfig.getInstance(App.getContext()).set("articleUrl", configJsonObject.getString("articleUrl"));
        AppConfig.getInstance(App.getContext()).set("problemUrl", configJsonObject.getString("problemUrl"));
        AppConfig.getInstance(App.getContext()).set("redBagUrl", configJsonObject.getString("redBagUrl"));
        AppConfig.getInstance(App.getContext()).set("qq", cusJsonObject.getString("qq"));
        AppConfig.getInstance(App.getContext()).set("iosGroupKeyUin", cusJsonObject.getString("iosGroupKeyUin"));
        AppConfig.getInstance(App.getContext()).set("iosGroupKey", cusJsonObject.getString("iosGroupKey"));
        AppConfig.getInstance(App.getContext()).set("wechat", cusJsonObject.getString("wechat"));
        AppConfig.getInstance(App.getContext()).set("qqGroup", cusJsonObject.getString("qqGroup"));
        AppConfig.getInstance(App.getContext()).set("groupKey", cusJsonObject.getString("groupKey"));
        AppConfig.getInstance(App.getContext()).set("wxNumber", cusJsonObject.getString("wxNumber"));
        AppConfig.getInstance(App.getContext()).set("articleUploadUrl", configJsonObject.getString("articleUploadUrl"));
        AppConfig.getInstance(App.getContext()).set("QQBrowserTip", configJsonObject.getString("QQBrowserTip"));
        AppConfig.getInstance(App.getContext()).set("WXLINETIP", configJsonObject.getString("WXLINETIP"));
        AppConfig.getInstance(App.getContext()).set("transfer_articleShareUrl", configJsonObject.getString("transfer_articleShareUrl"));
        AppConfig.getInstance(App.getContext()).set("pacg_appid", configJsonObject.getString("pacg_appid"));
        checkVersion();
    }

    //获取系统配置参数
    private void getConfig() {
        Task.getApiService().getConfig().enqueue(new MyCallback<NewsBaseEntity>(WelActivity.this) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
                if ("1".equals(response.body().getCode())) {
                    String jsonStr = JSONObject.toJSONString(response.body().getData());
                    JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                    String configuration = jsonObject.getString("configuration");//url配置信息
                    String customer = jsonObject.getString("customer");//客服配置信息
                    JSONObject configJsonObject = JSONObject.parseObject(configuration);
                    JSONObject cusJsonObject = JSONObject.parseObject(customer);
                    saveConfig(configJsonObject, cusJsonObject);
                } else {
                    NewsToastUtils.showToast(App.getContext(), "配置信息获取失败！");
                }
            }

            @Override
            protected void onFailure(Throwable t) {
                NewsToastUtils.showToast(App.getContext(), "配置信息获取失败！");
            }
        });
    }

    private void toActivity() {
        try {
            if (UserUtils.checkLogin()) {
                startActivity(new Intent(WelActivity.this, MainActivity.class));
                finish();
            } else {
                startActivity(new Intent(WelActivity.this, NewsLoginActivity.class));
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传快手的唯一标识
     */
    @SuppressLint("HardwareIds")
    private void upLoadUnique(boolean isOpen) {
        String mac = SPUtils.get(App.getContext(), "uniqueIdentifier", "00:00:00:00:00:02") + "";
        if ("00:00:00:00:00:02".equals(mac)) {
            if (SystemUtils.openWifi(App.getContext())) {//
                //表示已经打开wifi了
                mac = SystemUtils.getUniqueIdentifier(App.getContext());
                SPUtils.put(App.getContext(), "uniqueIdentifier", mac);//唯一标识
            }
        }
        String imei;
        if (isOpen) {
            imei = SystemUtils.getIMEI() + "";
        } else {
            imei = "";
        }
        String androidId = SystemUtils.getAndroidId();
        String lastUnique = androidId + Build.SERIAL;
        SPUtils.put(App.getContext(), "imei", imei);
        SPUtils.put(App.getContext(), "androidId", androidId);
        SPUtils.put(App.getContext(), "lastUnique", lastUnique);
        toActivity();
    }

    /**
     * 获取系统参数
     */
    private void getGlobalHeader() {
        String uniqueIdentifier = SPUtils.get(App.getContext(), "uniqueIdentifier", "00:00:00:00:00:02") + "";
        SPUtils.put(App.getContext(), "OSType", SystemUtils.getOSType()); //手机系统版本(iOS, Android)
        SPUtils.put(App.getContext(), "OSVersion", SystemUtils.getOSVersion());//手机系统版本号
        SPUtils.put(App.getContext(), "deviceModel", SystemUtils.getDeviceModel());//手机型号
        if ("00:00:00:00:00:02".equals(uniqueIdentifier)) {
            if (SystemUtils.openWifi(App.getContext())) {//
                //表示已经打开wifi了
                uniqueIdentifier = SystemUtils.getUniqueIdentifier(App.getContext());
            } else {
                SPUtils.put(App.getContext(), "uniqueIdentifier", uniqueIdentifier);//唯一标识
            }
        }
        SPUtils.put(App.getContext(), "appVersion", SystemUtils.getLocalVersion(App.getContext()) + "");//获取应用版本号

        checkVersion();
    }

    //打开其他的浏览器
    private void checkVersion() {
        Task.getApiService().checkNewsVersion().enqueue(new MyCallback<NewsBaseEntity>(WelActivity.this) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
                if ("1".equals(response.body().getCode())) {
                    String downLoadUrl = AppConfig.getInstance(App.getContext()).get("downLoadUrl");
                    String jsonStr = JSONObject.toJSONString(response.body().getData());
                    JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                    String str = jsonObject.getString("android");
                    JSONObject jsonObject_1 = JSONObject.parseObject(str);
                    String remoteVersion = jsonObject_1.getString("version");
                    String versionName = SystemUtils.getLocalVersionName(App.getContext());
                    if (!versionName.equals(remoteVersion)) {
                        new CenterDialog(R.layout.prompt_check_version, WelActivity.this).checkVersion(jsonObject_1.getString("remark"), downLoadUrl);
                    } else {
                        getPermission();
                    }

                } else {
                    NewsToastUtils.showToast(App.getContext(), response.body().getMsg());
                }
            }

            @Override
            protected void onFailure(Throwable t) {
                NewsToastUtils.showToast(App.getContext(), "网络请求失败！");
            }
        });
    }

    /**
     * 获取相关权限
     */
    private void getPermission() {
        PermissionUtils.getInstance().checkPermissions(this, PERMISSIONS, permissionsResult);
    }

    //创建监听权限的接口对象
    PermissionUtils.IPermissionsResult permissionsResult = new PermissionUtils.IPermissionsResult() {
        @Override
        public void passPermissons() {
            //当提示申请权限时，全部通过，会走这里（6.0以下直接走这里）
//            myHandler.sendEmptyMessageDelayed(0, 2000);
            upLoadUnique(true);
        }

        @Override
        public void forbitPermissons() {
            //只要有一个被拒绝，则会走这里，拒绝不在提醒，还是会走这里
//            myHandler.sendEmptyMessageDelayed(0, 2000);
            upLoadUnique(false);
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //回调结果
        PermissionUtils.getInstance().onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    //静态内部类handler，防止内存泄漏
    private static class MyHandler extends Handler {

        private WeakReference<WelActivity> mActivity;

        private MyHandler(WelActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Activity act = mActivity.get();
            if (act != null) {
//                boolean isFirst = (boolean) SPUtil.get(act.getApplicationContext(),
//                        Constant.CommonInfo.IS_FIRST, true);
                //引导页去掉
                boolean isFirst = false;
//                if (isFirst) {//首次打开
//                    act.startActivity(new Intent(act, GuideActivity.class));
//                } else {//非首次打开
                //同意权限后进行获取系统参数
                //获取header信息
                try {
                    if (UserUtils.checkLogin()) {
                        act.startActivity(new Intent(act, MainActivity.class));
                        act.finish();
                    } else {
                        act.startActivity(new Intent(act, NewsLoginActivity.class));
                        act.finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myHandler != null)
            myHandler.removeCallbacksAndMessages(null);
    }
}
